package com.chenfan.infra.service;

import com.alibaba.fastjson.JSONObject;
import com.chenfan.infra.utils.StringUtils;
import com.chenfan.infra.entity.SysOperLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 异步调用日志服务
 * 
 * @author ruoyi
 */
@Service
@Slf4j
public class AsyncLogService {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    public static final String SERVICE_NAME = "chenfan-cloud-log";

    @Value("${log.url:}")
    private String prefixUrl;
    /**
     * 保存系统日志记录
     */
    @Async
    public void saveSysLog(SysOperLog sysOperLog) {
        List<ServiceInstance> instances = discoveryClient.getInstances(SERVICE_NAME);
        if (CollectionUtils.isEmpty(instances)) {
            log.warn("实例={}暂未寻找到可用的服务列表", SERVICE_NAME);
            return;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        ServiceInstance serviceInstance = instances.stream().findAny().get();
        String uri = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort();
        if (!StringUtils.isEmpty(prefixUrl)) {
            uri = prefixUrl;
        }
        String url = uri + "/oper/log";

        String token = sysOperLog.getToken();
        if (!StringUtils.isEmpty(token)) {
            headers.add("Authorization", token);
        }

        HttpEntity<String> request = new HttpEntity<>(JSONObject.toJSONString(sysOperLog), headers);
        log.info("记录日志, 请求:{}, 请求参数：{}", url, JSONObject.toJSONString(sysOperLog));
        String postResult = restTemplate.postForObject(url, request, String.class);
        log.info("记录日志结果:{}", postResult);
    }
}
